package com.df.renren.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.df.renren.entity.SysUserEntity;
import com.df.renren.utils.Constant;
import com.df.renren.utils.EhcacheUtil;
import com.df.renren.utils.R;
import com.df.renren.utils.RRException;

/**
 * 
 * app token拦截
 * 
 * @author cdf
 *
 */
@Aspect
@Component
public class AppTokenInterceptor {

	private static final Logger log = Logger.getLogger(AppTokenInterceptor.class);

	private HttpServletRequest request = null;

	private HttpServletResponse response = null;

	// controller包的子包里面任何方法
	@Pointcut("execution(* com.df.renren.app.api.*Controller.*(..))")
	public void checkToken() {
	}

	@Before("checkToken()")
	public void beforeCheckToken() throws IOException {
		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	
		log.info("调用方法之前。。。。");
		String url = request.getRequestURI();
		if (!url.endsWith("/login")) {
			String token = request.getParameter("token");
			if (token == null) {
				token = request.getHeader("token");
				if(token == null){
					throw new RRException("token is not null", 40029);
				}
			}
			// do something
			EhcacheUtil util = EhcacheUtil.getInstance();
			SysUserEntity user = (SysUserEntity) util.get(Constant.APP_TOKEN_CACHENAME, token);
			if (user == null) {
				throw new RRException("token is expire", 40030);
			}
		}
	}

	// 抛出异常时才调用
	@AfterThrowing("checkToken()")
	public void afterThrowing() {
		log.error("app后台异常......");
	}

}
